package org.finesys.common.websocket.support;

import static org.springframework.messaging.simp.SimpMessageHeaderAccessor.USER_HEADER;
import static org.springframework.messaging.simp.stomp.StompHeaderAccessor.STOMP_LOGIN_HEADER;
import static org.springframework.messaging.support.NativeMessageHeaderAccessor.NATIVE_HEADERS;

import java.security.Principal;
import java.util.List;
import java.util.Map;

import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.messaging.AbstractSubProtocolEvent;

public class WebSocketHolder {

    /**
     * 获取用户信息
     */
    public static String getUserName(StompHeaderAccessor accessor) {
        //获取用户信息
        Principal principal = accessor.getUser();
        String userName = "";
        if (principal != null) {
            userName = principal.getName();
            return userName;
        }

        //是否存在头部信息
        if (accessor.containsNativeHeader(USER_HEADER)) {
            userName = accessor.getFirstNativeHeader(USER_HEADER);
            return userName;
        }
        //是否存在头部信息
        if (accessor.containsNativeHeader(STOMP_LOGIN_HEADER)) {
            userName = accessor.getLogin();
            return userName;
        }
        return userName;
    }


    /**
     * 获取用户信息
     */
    public static String getUserName(AbstractSubProtocolEvent abstractSubProtocolEvent) {
        //获取用户信息
        Principal principal = abstractSubProtocolEvent.getUser();
        String userName = "";
        if (principal != null) {
            userName = principal.getName();
            return userName;
        }
        MessageHeaders messageHeaders = abstractSubProtocolEvent.getMessage().getHeaders();
        //转为map
        Map<String, List<String>> map = (Map<String, List<String>>) messageHeaders.get(NATIVE_HEADERS);
        if (map != null) {
            //是否存在头部信息
            if (map.containsKey(USER_HEADER)) {
                userName = getFirstNativeHeader(map, USER_HEADER);
                return userName;
            }
            //是否存在头部信息
            if (map.containsKey(STOMP_LOGIN_HEADER)) {
                userName = getFirstNativeHeader(map, STOMP_LOGIN_HEADER);
                return userName;
            }
        }
        return userName;
    }

    public static String getFirstNativeHeader(Map<String, List<String>> map, String headerName) {
        if (map != null) {
            List<String> values = map.get(headerName);
            if (!CollectionUtils.isEmpty(values)) {
                return values.get(0);
            }
        }
        return null;
    }
}
